<?php


namespace app\sys\model;


use Kqtec\IpLocationZh\Ip;
use think\Db;
use think\facade\Request;
use think\Model;

class UrlSourceLog extends Model
{
    protected $autoWriteTimestamp = true;


    public function setBeUrlAttr($value):string
    {
        if(strlen($value) > 255){
            return mb_substr($value,254);
        }
        return $value;
    }

    public function setAfUrlAttr($value):string
    {
        if(strlen($value) > 255){
            return mb_substr($value,254);
        }
        return $value;
    }

    /**
     * @param $beUrl
     * @param $afUrl
     * @param $no
     */
    public static function add($beUrl,$afUrl,$no)
    {
        if($beUrl || $afUrl){
            if($beUrl) $beUrl = mb_substr($beUrl,0,200);
            if($afUrl) $afUrl = mb_substr($afUrl,0,200);

            $sourceName = visitSource($beUrl,$afUrl)[0];
            $site = UrlSourceLog::getSite(getComeUrl());

            $ip = Request::ip();

            $address = "";
            // 获取地址
            $arrAr = Ip::find($ip)["location"];
            if (!empty($arrAr)) {
                $address = implode("/", array_slice($arrAr, 1));
            }

            $arr = [
                "be_url"=>$beUrl,"af_url" => $afUrl,"no"=>$no,"site"=>$site,"source_name"=>$sourceName,
                "address"=>$address,
                "create_time"=>time()
                ,"ip" => $ip
            ];

            Db::name("url_source_log")->insert($arr);
        }
    }

    /**
     * @param $UserNo
     * @return string
     * 获取来源数据
     */
    public static function getSource($UserNo):array
    {
        $viData = ["非搜索引擎来源",""];
        $souData = UrlSourceLog::where("no",$UserNo)->order("create_time")->find();
        if($souData){
            $viData = visitSource($souData["be_url"],$souData["af_url"]);
        }
//        Dict::where("cate","source")->where("label",$viData)->value("value",1)
        return $viData;
    }

    /**
     * @param $UserNo
     * @return string
     * 获取来源数据
     */
    public static function getUrlIng($UserNo):string
    {
        if(!$UserNo)return "";
        $souDataArr = UrlSourceLog::where("no",$UserNo)->order("id desc")->column("af_url");
        if(!empty($souDataArr)){
            foreach ($souDataArr as $k => $v){
                if(strpos($v,"details")){
                    return $v;
                }
            }
        }
        return "";
    }

    /**
     * 获取站点
     * @param $url
     * @return string
     */
    public static function getSite($url):string
    {
        $arr = Dict::where("cate","site")->column("label","value");
        foreach ($arr as $k => $v){
            if (strpos($url,$v))
                return $v;
        }
        return $url;
    }
}